from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.urls import reverse
from django.db import transaction
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status
import json
import re
import logging
from datetime import datetime, timedelta

from psychology_login.models import User

logger = logging.getLogger(__name__)

# 页面视图
def register_view(request):
    """注册页面视图"""
    if request.user.is_authenticated:
        return redirect('main_page')
    return render(request, 'register_page.html')

# API视图
@api_view(['POST'])
@permission_classes([AllowAny])
def register_user(request):
    """用户注册API（不需要邮箱验证）"""
    try:
        data = request.data
        phone = data['phone']

        # 检查用户名是否已存在
        if User.objects.filter(username=data['username']).exists():
            return Response({
                'success': False,
                'message': '用户名已被占用',
                'code': 'username_exists'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 1. 验证手机号是否为空
        if not phone:
            return Response({
                'success': False,
                'message': '手机号不能为空',
                'code': 'phone_required'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 2. 验证手机号是否已存在
        if User.objects.filter(phone_number=phone).exists():
            return Response({
                'success': False,
                'message': '手机号已被注册',
                'code': 'phone_exists'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 创建用户
        with transaction.atomic():
            user = User.objects.create_user(
                username=data['username'],
                password=data['password'],
                first_name=data['first_name'],
                last_name=data['last_name'],
                is_active=True,  # 不需要邮箱验证，直接激活
                phone_number=phone,
            )

            # 创建用户档案
            # profile = User.objects.create(
            #     user=user,
            #     phone=validated_data['phone'],
            #     agree_newsletter=validated_data.get('agree_newsletter', False),
            #     registration_ip=get_client_ip(request),
            #     registration_date=datetime.now()
            # )

            logger.info(f"用户注册成功: {user.username}")

            return Response({
                'success': True,
                'message': '注册成功！请直接登录',
                'redirect_url': "",
                'user_id': user.id
            }, status=status.HTTP_201_CREATED)

    except Exception as e:
        logger.error(f"注册失败: {str(e)}")
        return Response({
            'success': False,
            'message': '注册失败，服务器错误',
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


